package cn.woochen.comlib.adapter

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView


/**
 * grid分割线 (GridLayoutManager分割线)
 * @param spacing 间隔
 * @param includeEdge 是否包含边缘
 */
class GridSpacingItemDecoration(private val spacing: Int, private val includeEdge: Boolean
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        var spanCount = 0
        if (parent.layoutManager is GridLayoutManager){
            spanCount = (parent.layoutManager as GridLayoutManager).spanCount
        }
        //这里是关键，需要根据你有几列来判断
        var realPosition = parent.getChildAdapterPosition(view) // item position
        val column = realPosition % spanCount // item column
        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount // (column + 1) * ((1f / spanCount) * spacing)

            if (realPosition < spanCount) { // top edge
                outRect.top = spacing
            }
            outRect.bottom = spacing // item bottom
        } else {
            outRect.left = column * spacing / spanCount // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (realPosition >= spanCount) {
                outRect.top = spacing // item top
            }
        }
    }

}
